﻿<template>
  <div>
    <div class="table-operator" style="margin-bottom: 20px">
      <a-button :disabled="disabled" type="primary" icon="plus" @click="hanldleAdd()">添加</a-button>&nbsp;
      <a-button type="primary" icon="minus" @click="handleDelete(selectedRows)" :disabled="!hasSelected() || disabled"
        >删除</a-button
      >
    </div>

    <a-table
      ref="table"
      :columns="disabled ? columns2 : columns"
      :rowKey="row => row.Id"
      :pagination="false"
      :dataSource="data"
      :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
      :bordered="true"
      size="small"
    >
      <!-- 批次 -->
      <template slot="Batch" slot-scope="text, record">
        <a-input
          v-if="record.Material.IsBatch"
          size="small"
          class="input"
          v-model="record.Batch"
          :disabled="disabled"
          style="text-align: right"
        ></a-input>
      </template>

      <!-- 有效期 -->
      <template slot="IsPeriodOfValidity" slot-scope="text, record">
        <a-input
          v-if="record.Material.IsPeriodOfValidity"
          size="small"
          class="input"
          type="number"
          :min="0"
          v-model="record.IsPeriodOfValidity"
          style="text-align: right"
        ></a-input>
      </template>
      <!-- 生产日期 -->
      <template slot="StartDate" slot-scope="text, record, index">
        <a-date-picker
          v-if="record.Material.IsPeriodOfValidity"
          valueFormat="YYYY-MM-DD"
          style="width: 85%"
          placeholder="请选择"
          @change="datechange(index)"
          :disabled="disabled"
          v-model="record.StartDate"
        />
      </template>
      <!-- 截止日 -->
      <template slot="EndDate" slot-scope="text, record, index">
        <a-date-picker
          placeholder="请选择"
          v-if="record.Material.IsPeriodOfValidity"
          valueFormat="YYYY-MM-DD"
          style="width: 85%"
          @change="EndDatechange(index)"
          :disabled="disabled"
          v-model="record.EndDate"
          :disabled-date="disabledDate"
        />
      </template>

      <!-- 保质月数 -->
      <template slot="NumberDate" slot-scope="text, record">
        <a-input
          v-if="record.Material.IsPeriodOfValidity"
          size="small"
          class="input"
          :disabled="disabled"
          type="number"
          :min="0"
          v-model="record.NumberDate"
          style="text-align: right"
        ></a-input>
      </template>
      <template slot="PlanNum" slot-scope="text, record">
        <a-input-number
          size="small"
          :disabled="disabled"
          :value="text"
          :min="0"
          style="text-align: right"
          @change="e => handleValChange(e, record)"
        ></a-input-number>
      </template>
      <template slot="Price" slot-scope="text, record">
        <a-input-number
          size="small"
          :disabled="disabled"
          :value="text"
          step="1"
          :min="0"
          @change="e => handlePriceChange(e, record)"
        ></a-input-number>
      </template>
      <template slot="TaxRate" slot-scope="text, record">
        <a-input-number
          size="small"
          :disabled="disabled"
          :value="text"
          :min="0"
          @change="e => handleTaxRateChange(e, record)"
        ></a-input-number>
      </template>
      <template slot="SupId" slot-scope="text, record">
        <sup-select v-model="record.SupId" :disabled="disabled"></sup-select>
      </template>

      <span slot="action" slot-scope="text, record">
        <template>
          <a :disabled="disabled" @click="handleDelete([record])">删除</a>
        </template>
      </span>
    </a-table>

    <material-choose ref="materialChoose" @onChoose="handerMaterialChoose" :id="RefCode"></material-choose>
  </div>
</template>

<script>
import moment from 'moment'
// import SupSelect from '@/components/PB/SupplierSelect.vue'
// import MaterialChoose from '@/components/hospitalComponents/MaterialChoose.vue'
const columns = [
  {
    title: '序号',
    dataIndex: 'Id',
    customRender: (text, row, index) => {
      return index + 1
    },
    width: '50px'
  },
  { title: '物品名称', dataIndex: 'Material.Name' },
  { title: '物品编码', dataIndex: 'Material.Code' },
  { title: '物品规格', dataIndex: 'Material.Spec' },
  // { title: '供货单位', dataIndex: 'SupId', scopedSlots: { customRender: 'SupId' } },

  // { title: '税率(%)', dataIndex: 'TaxRate', scopedSlots: { customRender: 'TaxRate' }, align: 'right', width: '120px' },

  // { title: '物品单价', dataIndex: 'Price', scopedSlots: { customRender: 'Price' }, align: 'right' },
  { title: '数量', dataIndex: 'PlanNum', scopedSlots: { customRender: 'PlanNum' }, align: 'right', width: '120px' },
  // { title: '总价', dataIndex: 'Amount', align: 'right' },
  {
    title: '批次号',
    dataIndex: 'Batch',
    scopedSlots: { customRender: 'Batch' },
    align: 'right',
    width: '140px'
  },

  {
    title: '生产日期',
    dataIndex: 'StartDate',
    scopedSlots: { customRender: 'StartDate', width: '120px' }
  },
  {
    title: '截止日期',
    dataIndex: 'EndDate',
    scopedSlots: { customRender: 'EndDate', width: '120px' }
  },
  // {
  //   title: '有效期(月)',
  //   dataIndex: 'IsPeriodOfValidity',
  //   scopedSlots: { customRender: 'IsPeriodOfValidity' },
  //   align: 'right'
  // },
  {
    title: '保质月数',
    dataIndex: 'NumberDate',
    scopedSlots: { customRender: 'NumberDate' },
    align: 'right',
    width: '100px'
  },
  { title: '操作', dataIndex: 'action', scopedSlots: { customRender: 'action' } }
]
const columns2 = [
  {
    title: '序号',
    dataIndex: 'Id',
    customRender: (text, row, index) => {
      return index + 1
    },
    width: '50px'
  },
  { title: '物品名称', dataIndex: 'Material.Name' },
  { title: '物品编码', dataIndex: 'Material.Code' },
  { title: '物品规格', dataIndex: 'Material.Spec' },
  // { title: '供货单位', dataIndex: 'Supplier.Name' },
  // , scopedSlots: { customRender: 'SupId' }
  // { title: '税率(%)', dataIndex: 'TaxRate', align: 'right' },

  // { title: '物品单价', dataIndex: 'Price', align: 'right' },
  { title: '数量', dataIndex: 'PlanNum', align: 'right' },
  // { title: '总价', dataIndex: 'Amount', align: 'right' },
  {
    title: '批次号',
    dataIndex: 'Batch',
    // scopedSlots: { customRender: 'Batch' },
    align: 'right',
    width: '140px'
  },
  {
    title: '生产日期',
    dataIndex: 'StartDate',
    customRender: value => {
      if (value) return value.substring(0, 10)
    }
    // scopedSlots: { customRender: 'StartDate', width: '120px' },
  },
  {
    title: '截止日期',
    dataIndex: 'EndDate',
    customRender: value => {
      if (value) return value.substring(0, 10)
    }
    // scopedSlots: { customRender: 'EndDate', width: '120px' },
  },

  {
    title: '保质月数',
    dataIndex: 'NumberDate',
    scopedSlots: { customRender: 'NumberDate' },
    align: 'right',
    width: '100px'
  },
  { title: '操作', dataIndex: 'action', scopedSlots: { customRender: 'action' } }
]

export default {
  components: {
    // MaterialChoose,
    // SupSelect
  },
  props: {
    value: { type: Array, required: true },
    disabled: { type: Boolean, required: false, default: false },
    RefCode: { type: String, required: false, default: '' }
  },
  data() {
    return {
      data: [],
      rules: {
        StartDate: [{ required: true, message: '请输入订单时间', trigger: 'change' }]
      },
      columns2,
      ind: null,
      columns,
      tempId: 0,
      selectedRowKeys: [],
      selectedRows: [],
      flag: true
    }
  },
  watch: {
    value(val) {
      console.log(val)
      // this.value = val
      this.data = [...this.value]

      this.data.forEach(item => {
        if (item.EndDate) {
          let date1 = item.EndDate.split('-')
          date1 = parseInt(date1[0]) * 12 + parseInt(date1[1])
          let date2 = item.StartDate.split('-')
          date2 = parseInt(date2[0]) * 12 + parseInt(date2[1])
          item.NumberDate = date1 - date2
        }

        if (!this.disabled) {
          if (item.StartDate) item.StartDate = moment(item.StartDate)
          if (item.EndDate) item.EndDate = moment(item.EndDate)
        }
        item.Amount = Number(item.PlanNum) * Number(item.Price)
        // item.Amount = item.Amount.replace(/[^\d.]/g, '') //清除“数字”和“.”以外的字符
        // item.Amount = item.Amount.replace(/\.{2,}/g, '.') //只保留第一个. 清除多余的
        // item.Amount = item.Amount.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.')
        // item.Amount = item.Amount.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3') //只能输入两个小数
        item.Amount = item.Amount.toFixed(2)
        if (item.InNum != '' || item.InNum != undefined || item.InNum != null) {
          item.InNum = item.InNum + ''
          item.InNum = item.InNum.replace(/[^\d.]/g, '') //清除“数字”和“.”以外的字符
          item.InNum = item.InNum.replace(/\.{2,}/g, '.') //只保留第一个. 清除多余的
          item.InNum = item.InNum.replace('.', '$#$')
            .replace(/\./g, '')
            .replace('$#$', '.')
          item.InNum = item.InNum.replace(/^(\-)*(\d+)\.(\d\d\d\d).*$/, '$1$2.$3') //只能输入4个小数
        }
      })
      console.log(this.data)
    }
  },
  mounted() {
    // this.data = [...this.value]
  },
  methods: {
    datechange(index) {
      console.log(index)
      console.log(this.data)
      this.ind = index
      this.$set(this.data[index], 'EndDate', null)
      this.$set(this.data[index], 'NumberDate', null)
    },
    EndDatechange(index) {
      // console.log(index)
      // this.ind = index
    },
    disabledDate(current) {
      // console.log(this.ind)
      const startValue = this.data[this.ind].StartDate

      if (startValue) {
        return startValue.valueOf() >= current.valueOf()
      } else {
        return current.valueOf() <= moment().subtract(1, 'days')
      }
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    hasSelected() {
      return this.selectedRowKeys.length > 0
    },
    hanldleAdd() {
      this.$refs.materialChoose.openChoose()
    },
    handerMaterialChoose(materials) {
      console.log(materials)
      console.log(this.data)
      this.flag = true
      if (this.data.length <= 0) {
        materials.forEach(val => {
          this.$set(val, 'PlanNum', 1)
          this.tempId += 1
          var curDetail = {
            Id: 'newid_' + this.tempId.toString(),
            Material: val,
            materialId: val.Id,
            StorId: val.StorId
          }
          this.$set(curDetail, 'PlanNum', 0)
          this.$set(curDetail, 'Price', val.Price)
          this.$set(curDetail, 'Amount', 0)

          this.data.push({ ...curDetail })
          console.log(this.data)
        })
      } else {
        var arr = [...materials]
        console.log(this.data, 222)
        this.data.forEach(item => {
          arr.forEach((val, i) => {
            if (val.Code == item.Material.Code) {
              this.flag = false
              delete arr[i]
            }
          })
        })
        console.log(arr)
        arr.forEach(val => {
          this.tempId += 1
          var curDetail = {
            Id: 'newid_' + this.tempId.toString(),
            Material: val,
            materialId: val.Id,
            StorId: val.StorId
          }
          this.$set(curDetail, 'PlanNum', 0)
          this.$set(curDetail, 'Price', val.Price)
          this.$set(curDetail, 'Amount', (Number(curDetail.PlanNum) * Number(curDetail.Material.Price)).toFixed(2))

          this.data.push({ ...curDetail })
        })
        if (!this.flag) {
          this.$message.error('重复物品已筛选掉')
        }
        // this.data = [...this.data, ...arr]
      }

      console.log(this.flag)
      this.$emit('input', [...this.data])
    },
    handleDelete(items) {
      var thisObj = this
      this.$confirm({
        title: '确认删除吗?',
        onOk() {
          return new Promise((resolve, reject) => {
            items.forEach(element => {
              var index = thisObj.data.indexOf(element)
              thisObj.data.splice(index, 1)
              var keyIndex = thisObj.selectedRowKeys.indexOf(element.Id)
              thisObj.selectedRowKeys.splice(keyIndex, 1)
            })
            thisObj.$emit('input', [...thisObj.data])
            resolve()
          })
        }
      })
    },
    handleTaxRateChange(val, item) {
      item.TaxRate = val
      this.$emit('input', [...this.data])
    },
    handlePriceChange(val, item) {
      console.log(val)
      console.log(item)
      item.Price = val + ''
      item.Price = item.Price.replace(/[^\d.]/g, '') //清除“数字”和“.”以外的字符
      item.Price = item.Price.replace(/\.{2,}/g, '.') //只保留第一个. 清除多余的
      item.Price = item.Price.replace('.', '$#$')
        .replace(/\./g, '')
        .replace('$#$', '.')
      item.Price = item.Price.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3') //只能输入两个小数
      // if (val.indexOf('.') < 0 && val != '') { //以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
      //   val = parseFloat(val)
      // }
      // item.Amount = (Math.round(Number(item.PlanNum)) * Number(val)).toFixed(2)
      item.Amount = Math.floor(Number(item.PlanNum)) * Number(item.Price) + ''
      item.Amount = item.Amount.replace(/[^\d.]/g, '') //清除“数字”和“.”以外的字符
      item.Amount = item.Amount.replace(/\.{2,}/g, '.') //只保留第一个. 清除多余的
      item.Amount = item.Amount.replace('.', '$#$')
        .replace(/\./g, '')
        .replace('$#$', '.')
      item.Amount = item.Amount.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3') //只能输入两个小数
      this.$emit('input', [...this.data])
    },
    handleValChange(val, item) {
      console.log(val)
      console.log(item)
      item.PlanNum = val + ''
      item.PlanNum = item.PlanNum.replace(/[^\d.]/g, '') //清除“数字”和“.”以外的字符
      item.PlanNum = item.PlanNum.replace(/\.{2,}/g, '.') //只保留第一个. 清除多余的
      item.PlanNum = item.PlanNum.replace('.', '$#$')
        .replace(/\./g, '')
        .replace('$#$', '.')
      item.PlanNum = item.PlanNum.replace(/^(\-)*(\d+)\.(\d\d\d\d).*$/, '$1$2.$3') //只能输入4个小数

      item.Amount = Number(item.PlanNum) * Number(item.Price) + ''
      item.Amount = item.Amount.replace(/[^\d.]/g, '') //清除“数字”和“.”以外的字符
      item.Amount = item.Amount.replace(/\.{2,}/g, '.') //只保留第一个. 清除多余的
      item.Amount = item.Amount.replace('.', '$#$')
        .replace(/\./g, '')
        .replace('$#$', '.')
      item.Amount = item.Amount.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3') //只能输入两个小数
      // item.Price = Number(item.Material.Price)
      this.$emit('input', [...this.data])
    }
  }
}
</script>
